package com.study.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {

    private String name;

    private StringRedisTemplate redisTemplate;

    private static final String key_prefix = "lock:";

    private static final String id_prefix = UUID.randomUUID().toString(true)+"-";
    
    private static final DefaultRedisScript<Long> redisScript;
    static {
        redisScript = new DefaultRedisScript<>();
        redisScript.setLocation(new ClassPathResource("unloac.lua"));
        redisScript.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate redisTemplate) {
        this.name = name;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        String value = id_prefix+Thread.currentThread().getId();
        Boolean isLock = redisTemplate.opsForValue().setIfAbsent(key_prefix + name, value, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(isLock);
    }

    @Override
    public void unLock() {
        redisTemplate.execute(redisScript, Collections.singletonList(key_prefix + name),
                id_prefix+Thread.currentThread().getId());
    }
    
    /*@Override
    public void unLock() {
        String value = id_prefix+Thread.currentThread().getId();
        String redisValue = redisTemplate.opsForValue().get(key_prefix + name);
        if(value.equals(redisValue)){
            //释放锁
            redisTemplate.delete(key_prefix + name);
        }

    }*/
}
